package com.mini.rpc.provider;

import com.mini.rpc.annotation.RpcService;
import com.mini.rpc.core.ServiceMeta;
import com.mini.rpc.protocol.codec.MiniRpcDecoder;
import com.mini.rpc.protocol.codec.MiniRpcEncoder;
import com.mini.rpc.protocol.handler.RpcRequestHandler;
import com.mini.rpc.register.RegistryService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lbx
 * @version 1.0.0
 * @description TODO
 * @date 2021/10/5 9:52
 **/
@Slf4j
public class RpcProvider implements InitializingBean, BeanPostProcessor {

    private String serverAddress;

    private final int servicePort;

    private final RegistryService registryService;

    private final Map<String, Object> rpcServiceMap = new HashMap<>();


    public RpcProvider(int servicePort, RegistryService registryService) {
        this.servicePort = servicePort;
        this.registryService = registryService;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        new Thread(()->{
            try {
                startRpcServer();
            } catch (Exception e) {
                log.error("start rpc server error.", e);
            }
        }).start();

    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        RpcService rpcService = bean.getClass().getAnnotation(RpcService.class);
        if (rpcService != null) {
            String serviceName = rpcService.serviceInterface().getName();
            String serviceVersion = rpcService.serviceVersion();
            try {
                ServiceMeta serviceMeta = new ServiceMeta();
                serviceMeta.setServiceAddr(serverAddress);
                serviceMeta.setServicePort(servicePort);
                serviceMeta.setServiceName(serviceName);
                serviceMeta.setServiceVersion(serviceVersion);
                registryService.register(serviceMeta);
                String serviceKey = String.join("#", serviceMeta.getServiceName(), serviceMeta.getServiceVersion());
                rpcServiceMap.put(serviceKey, bean);
            } catch (Exception e) {
                log.error("failed to register service {}#{}", serviceName, serviceVersion, e);
            }
        }
        return bean;
    }


    private void startRpcServer() throws Exception {
        this.serverAddress = InetAddress.getLocalHost().getHostAddress();
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                           socketChannel.pipeline()
                                   .addLast(new MiniRpcEncoder())
                                   .addLast(new MiniRpcDecoder())
                                   .addLast(new RpcRequestHandler(rpcServiceMap));
                        }
                    })
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
            ;

            ChannelFuture channelFuture = bootstrap.bind(this.serverAddress, this.servicePort).sync();
            log.info("server addr {} started on port {}", this.serverAddress, this.servicePort);
            channelFuture.channel().closeFuture().sync();

        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
